<template>
  <view class="container">
    <!-- <u-navbar
      title="生产记录"
      :autoBack="true"
      bgColor="#5284c1"
      titleStyle="color:#fff"
      leftIconColor="#fff"
      :fixed="false"
    ></u-navbar> -->
    <pap-navbar title="生产记录" back titleColor="#fff" bgColor="#5284c1" />
    <view class="info">
      <view>
        <!-- 0水泥 1水稳 2沥青 -->
        项目标段&nbsp;&nbsp;&nbsp;&nbsp;{{
          info.tendersName ? info.tendersName : '-'
        }}</view
      >
      <view>
        设备名称&nbsp;&nbsp;&nbsp;&nbsp;{{ info.name ? info.name : '-' }}</view
      >
      <view class="time_box">
        <view class="time_frame">
          <view @click="hamdleTime(2)">{{ startTime }}</view>
          -
          <view @click="hamdleTime(1)">{{ endTime }}</view>
        </view>
        <u-button class="time_btn" text="清空" @click="resetTime"></u-button>
      </view>
    </view>
    <view class="tips" style="display: flex; justify-content: space-between">
      <view>共 {{ total }} 条数据</view>
      <view
        class="analysis"
        v-if="type == 1"
        @click="handleSwitchAnalysis(`pages/common/stability/analysis`)"
        >产能分析</view
      >
      <view
        class="analysis"
        v-else-if="type == 2"
        @click="handleSwitchEchart('pages/common/asphalt/echart')"
        >分析曲线</view
      >
    </view>
    <scroll-view class="grow min-h-0" scroll-y="true">
      <template v-if="dataList.length > 0 || flag">
        <view
          @click="handleSwitch(item)"
          v-for="(item, index) in dataList"
          class="list_box"
          :key="index"
        >
          <view class="icon">
            <image
              :src="
                item.diskAlarmGrade
                  ? [
                      '/static/images/20211027-165339.png',
                      '/static/images/20211025-155755.png',
                      '/static/images/20211025-155841.png'
                    ][item.diskAlarmGrade - 1]
                  : '/static/images/20211025-160148.png'
              "
              style="width: 20px; height: 25px"
              mode=""
            >
            </image>
            <view
              :style="{
                color: item.diskAlarmGrade
                  ? ['#fcca00', '#ff6200', '#ff2525'][item.diskAlarmGrade - 1]
                  : '#1b9b35'
              }"
            >
              <template v-if="item.diskAlarmGrade">
                {{
                  ['初级超标', '中级超标', '高级超标'][item.diskAlarmGrade - 1]
                }}
              </template>
              <template v-else>合格</template>
            </view>
          </view>
          <view>
            <!-- 水泥 -->
            <view class="title_box" v-if="type == 0">
              <view class="title">
                <view>配比名称：{{ item.constructionMixProportionName }}</view>
                <view>实际方量：{{ item.actualTotal || '-' }}m³ </view>
                <view>出料时间：{{ item.dischargeTime }} </view>
              </view>
              <u-icon name="arrow-right"></u-icon>
            </view>
            <!-- 水稳 -->
            <view class="title_box" v-else-if="type == 1">
              <view class="title">
                <view
                  >配比名称：{{ item.proportionMixtureStabilizedName }}
                </view>
                <view>出料时间：{{ item.dischargeTime }} </view>
                <view
                  >盘重(kg)：{{ item.actualTotal ? item.actualTotal : '-' }}
                </view>
              </view>
              <u-icon name="arrow-right"></u-icon>
            </view>
            <!-- 沥青 -->
            <view class="title_box" v-else-if="type == 2">
              <view class="title">
                <view>生产面层：{{ item.worksSurfaceCourse }} </view>
                <view>生产重量：{{ item.actualTotal }} </view>
                <view>出料时间：{{ item.dischargeTime }} </view>
              </view>
              <u-icon name="arrow-right"></u-icon>
            </view>
          </view>
        </view>
      </template>
      <template v-else>
        <u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png">
        </u-empty>
      </template>

      <!-- 水稳 -->
      <u-datetime-picker
        :show="timeShow"
        v-model="timeValue"
        mode="date"
        @confirm="handleConfirm"
        @cancel="handleCancel"
      ></u-datetime-picker>
      <u-toast ref="uToast"></u-toast>
    </scroll-view>
  </view>
</template>

<script>
import { getStabilityListApi } from '@/api/mixing-plant/stability'
import { getCementListApi } from '@/api/mixing-plant/cement'
import { getAsphaltListApi } from '@/api/mixing-plant/asphalt'
import dayjs from '@/utils/dayjs'
export default {
  data() {
    return {
      currentTime: '',
      endTime: dayjs().format('YYYY-MM-DD'),
      startTime: dayjs().subtract(1, 'month').format('YYYY-MM-DD'),
      timeShow: false,
      timeValue: Number(new Date()),
      // 0水泥 1水稳 2沥青
      type: 10,
      dataList: [],
      params: {
        pageNumber: 1,
        pageSize: 10
      },
      info: {},
      total: '',
      currentNum: '',
      machine: '',
      flag: false,
      first: true
    }
  },
  watch: {
    endTime(newVal, oldVal) {
      if (newVal != '' && this.startTime != '') {
        this.params.pageNumber = 1
        this.dataList = []
        this.$nextTick(() => {
          if (this.type == 0) {
            // 水泥
            this.getCement()
          } else if (this.type == 1) {
            // 水稳
            this.getWaterstability()
          } else {
            // 沥青
            this.getLiqingList()
          }
        })
      }
    },
    startTime(newVal, oldVal) {
      if (newVal != '' && this.endTime != '') {
        this.params.pageNumber = 1
        this.dataList = []
        this.$nextTick(() => {
          if (this.type == 0) {
            // 水泥
            this.getCement()
          } else if (this.type == 1) {
            // 水稳
            this.getWaterstability()
          } else {
            // 沥青
            this.getLiqingList()
          }
        })
      }
    }
  },
  async onLoad(options) {
    if (options) {
      this.type = options.type
      this.info = JSON.parse(
        decodeURIComponent(decodeURIComponent(options.info))
      )
      if (this.type == 0) {
        // 水泥
        this.machine = options.num
        this.getCement()
        // this.getCementRecordDetail();
      } else if (this.type == 1) {
        // 水稳
        this.currentNum = options.num
        this.getWaterstability()
      } else {
        // 沥青
        // this.machine = options.id;
        // this.info = JSON.parse(JSON.parse(options.query).item);
        this.info.name = this.info.equipmentName
        this.getLiqingList()
      }
      console.log(this.dataList)
    }
  },
  methods: {
    formattedDate(date) {
      let year = date.getFullYear()
      let month = '0' + (date.getMonth() + 1) // 加1因为月份从0开始
      let day = '0' + date.getDate()
      let formattedDate = year + '-' + month.substr(-2) + '-' + day.substr(-2)
      return formattedDate
    },

    // 重置时间
    resetTime() {
      this.startTime = ''
      this.endTime = ''
    },
    hamdleTime(val) {
      this.currentTime = val
      this.timeShow = true
    },
    handleCancel() {
      this.timeShow = false
    },
    // 判断所选时间是否超过一个月
    determineTime(first, last) {
      console.log(first, last)
      let diffInMilliseconds =
        new Date(last.replace(/\-/g, '/')) - new Date(first.replace(/\-/g, '/'))
      let daysApart = Math.abs(diffInMilliseconds / (1000 * 60 * 60 * 24))
      return daysApart <= 31
    },
    // 时间组件点确认
    handleConfirm(value) {
      let res
      if (this.currentTime == 1 && this.startTime != '') {
        res = this.determineTime(
          // new Date(value.value).toLocaleDateString('zh-CN'),
          this.formattedDate(new Date(value.value)),
          this.startTime
        )
      } else if (this.currentTime == 2 && this.endTime != '') {
        res = this.determineTime(
          this.endTime,
          this.formattedDate(new Date(value.value))
        )
      } else {
        res = true
      }
      if (res) {
        const date = new Date(value.value)
        let formattedDate = this.formattedDate(date)
        this.currentTime == 1
          ? (this.endTime = formattedDate)
          : (this.startTime = formattedDate)
        this.timeShow = false
      } else {
        uni.showToast({
          title: '跨度超过一个月',
          duration: 2000,
          icon: 'error'
        })
      }
    },
    scrolltolower() {
      if (
        this.total > this.params.pageNumber * this.params.pageSize &&
        !this.flag
      ) {
        this.params.pageNumber++
        // console.log(
        //   this.params.pageNumber,
        //   '====================pageNumber======='
        // )
        if (this.type == 0) {
          // 水泥
          this.getCement()
        } else if (this.type == 1) {
          // 水稳
          this.getWaterstability()
        } else if (this.type == 2) {
          // 沥青
          this.getLiqingList()
        }
      } else if (
        this.total <= this.params.pageNumber * this.params.pageSize &&
        !this.flag
      ) {
        uni.showToast({
          title: '没有更多',
          icon: 'error',
          duration: 2000
        })
      }
    },
    // 获取水稳
    async getWaterstability() {
      uni.showLoading({
        title: '加载中',
        mask: true
      })
      this.flag = true
      let params = {
        pageNumber: this.params.pageNumber,
        pageSize: this.params.pageSize
      }
      let data = {
        equipmentNos: [this.info.num],
        dischargeStartTime: this.startTime + ' 00:00:00',
        dischargeEndTime: this.endTime + ' 23:59:59',
        // dischargeStartTime: "2024-2-26 00:00:00",
        // dischargeEndTime: "2024-2-27 23:59:59",
        proportionMixtureStabilizedName: '',
        matchState: ''
      }
      try {
        let res = await getStabilityListApi(params, data)
        res.records.forEach((val) => {
          val.dischargeTime = dayjs(val.dischargeTime).format(
            'YYYY-MM-DD HH:mm:ss'
          )
          val.constructionMixProportionName = val.constructionMixProportionName
            ? val.constructionMixProportionName
            : '-'
          this.dataList.push(val)
        })
        this.total = res.total
        uni.hideLoading()
      } catch (error) {
        uni.hideLoading()
      }
      this.flag = false
    },
    // 获取水泥
    async getCement() {
      this.flag = true
      uni.showLoading({
        title: '加载中',
        mask: true
      })
      let params = {
        pageNumber: this.params.pageNumber,
        pageSize: this.params.pageSize
      }
      let data = {
        dischargeStartTime: this.startTime + ' 00:00:00',
        dischargeEndTime: this.endTime + ' 23:59:59',
        // dischargeStartTime: '2024-05-01 00:00:00',
        // dischargeEndTime: '2024-05-01 23:59:59',
        equipmentNoList: [this.info.num],
        strengthGrade: '',
        projectName: '',
        pouringLocation: '',
        matchState: '',
        plateNumber: ''
      }
      try {
        let res = await getCementListApi(params, data)
        res.records.forEach((val) => {
          val.dischargeTime = dayjs(val.dischargeTime).format(
            'YYYY-MM-DD HH:mm:ss'
          )
          val.constructionMixProportionName = val.constructionMixProportionName
            ? val.constructionMixProportionName
            : '-'
          this.dataList.push(val)
        })
        this.total = res.total
        uni.hideLoading()
      } catch (error) {
        uni.hideLoading()
      }
      this.flag = false
    },
    // 获取沥青
    async getLiqingList() {
      uni.showLoading({
        title: '加载中',
        mask: true
      })
      let params = {
        pageNumber: this.params.pageNumber,
        pageSize: this.params.pageSize
      }
      let data = {
        itemId: '',
        sectionId: '',
        regionId: '',
        equipmentNoList: [this.info.equipmentNo],
        // equipmentNoList: ["e9equipment_20240116113543f44471a8"],
        dischargeStartTime: this.startTime + ' 00:00:00',
        dischargeEndTime: this.endTime + ' 23:59:59',
        // schargeStartTime: "2020-09-02 00:35:50",
        // dischargeEndTime: "2020-09-05 18:35:50",
        worksSurfaceCourse: '',
        matchingName: '',
        worksArea: '',
        matchState: ''
      }
      let res = await getAsphaltListApi(params, data)
      res.records.forEach((item) => {
        item.worksSurfaceCourse = item.worksSurfaceCourse ?? '-'
        item.dischargeTime = item.dischargeTime
          ? dayjs(item.dischargeTime).format('YYYY-MM-DD HH:mm:ss')
          : '-'
        item.actualTotal = item.actualTotal ?? '-'
      })
      this.dataList = this.dataList.concat(res.records)
      this.total = res.total
      uni.hideLoading()
    },
    handleSwitchAnalysis(url) {
      console.log(this.info)
      //   uni.navigateTo({
      //     url: `${url}?info=${JSON.stringify(this.info)}`,
      //   });
      this.$Router.push({
        name: 'stabilityAnalysis',
        params: this.info
      })
    },
    handleSwitchEchart(url) {
      uni.navigateTo({
        url: `${url}?id=${this.machine}`
      })
    },
    handleSwitch(item) {
      console.log(item)
      let obj = item
      //   console.log(item);
      //   if (this.type == 0 || this.type == 2) {
      // 水泥
      //   }
      uni.navigateTo({
        url: `/pages/common/component/detail/index?type=${this.type}&item=${item.dataCode}`
      })
      //   this.$Router.push({
      //     name: "mixStationDetail",
      //     data: obj,
      //   });
    }
  }
}
</script>
<style lang="scss" scoped>
.container {
  padding: 0px 0 40rpx;
  ::v-deep .u-cell__left-icon-wrap.data-v-1c4434ae {
    margin-right: 4px;
    width: 25%;
    display: flex;
    justify-content: center;
  }
  .analysis {
    width: 140rpx;
    height: 48rpx;
    line-height: 48rpx;
    border-radius: 20px;
    background-color: rgba(64, 133, 197, 1);
    text-align: center;
    color: #fff;
  }
  .info {
    background-color: #fff;
    padding: 40rpx;
    & > view:nth-child(1) {
      margin-bottom: 20rpx;
    }
    & > view {
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
  }
}

::v-deep {
  .u-line {
    display: none;
  }
  .icon {
    display: flex;
    align-items: center;
    flex-direction: column;
  }
}
.time_box {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
  height: 60rpx;

  .time_frame {
    width: 80%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    view {
      width: 45%;
      box-sizing: border-box;
      // background-color: pink;
      border: 1px solid #eaeae0;
      height: 60rpx;
      border-radius: 20rpx;
      text-align: center;
      line-height: 60rpx;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
  }

  /deep/ .u-button {
    width: 50px;
    height: 60rpx;
  }
}
#scrollView {
  background-color: #f7f7f7;
  width: 100%;

  .list_box {
    display: flex;
    width: 100%;
    background-color: #fff;
    padding: 20rpx 34rpx;
    margin: 20rpx 0;
    .icon {
      margin-right: 20rpx;
      width: 30vw;
      display: flex;
      justify-content: center;
      align-items: center;
      text-align: center;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
      img {
        height: 80rpx;
        width: 60rpx;
        margin-left: 8rpx;
      }
    }
    .title_box {
      flex: 1;
      display: flex;
      justify-content: space-between;
      .title {
        view {
          width: 65vw;
          margin: 10rpx 0;
          text-overflow: ellipsis; /* 溢出显示省略号 */
          overflow: hidden; /* 溢出隐藏 */
          white-space: nowrap; /* 强制不换行 */
        }
      }
    }
  }
}

// ::v-deep .list_box {
//   display: flex;
//   align-items: center;
//   padding: 20rpx 34rpx;
//   margin: 20rpx 0;
//   background-color: #fff;
//   width: 100%;
//   .icon {
//     display: block;
//     width: 50% !important;
//     // width: 50%;
//     // background-color: pink;
//     // margin-right: 40rpx;
//     font-size: 14px;
//     text-align: center;
//     // text-overflow: ellipsis;
//     // overflow: hidden;
//     // white-space: nowrap;
//     img {
//       height: 80rpx;
//       width: 60rpx;
//       margin-left: 8rpx;
//     }
//   }
//   .title_box {
//     // width: 80%;
//     display: flex;
//     justify-content: space-between;
//     .title {
//       view {
//         margin: 10rpx;
//         text-overflow: ellipsis; /* 溢出显示省略号 */
//         overflow: hidden; /* 溢出隐藏 */
//         white-space: nowrap; /* 强制不换行 */
//       }
//     }
//   }
// }
</style>
